package com.spring.web.adminmanage.interceptor;

import com.spring.web.adminmanage.entities.Menu;
import com.spring.web.adminmanage.entities.User;
import com.spring.web.adminmanage.service.LoginService;
import com.spring.web.adminmanage.service.MenuService;
import com.spring.web.adminmanage.service.UserLoginLogService;
import com.spring.web.adminmanage.service.WebUserService;
import com.spring.web.adminmanage.utils.CookieUtil;
import com.spring.web.adminmanage.utils.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 登录验证拦截器
 *
 * @author lilinfeng
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    LoginService loginService;
    @Autowired
    WebUserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    UserLoginLogService userLoginLogService;
    private final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // FIXME 请求结束之后
    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // FIXME 请求处理之后

    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        //请求处理之前
        Cookie[] cookies = request.getCookies();
//        String remoteAddr = request.getRemoteAddr();
        String remoteAddr = IPUtil.getRemortIP(request);
        Object attribute = request.getSession().getAttribute("loginUser");
        if (attribute != null) {
            request.getSession().setMaxInactiveInterval(10 * 60 * 60);
            setServerSession(request.getSession(),(User) attribute);
            return true;
        }
        if (cookies != null) {
            Cookie uid = CookieUtil.getCookie(cookies, "uid");
            Cookie sid = CookieUtil.getCookie(cookies, "sid");
            if (uid != null && sid != null && loginService.cookieVerification(uid.getValue(), sid.getValue(), remoteAddr)) {
                User userdata = userService.getUserByUsername(new User(uid.getValue()));
                userLoginLogService.addLoginLog(userdata.getId(), remoteAddr);
                request.getSession().setAttribute("loginUser", userdata);
                setServerSession(request.getSession(),userdata);
                request.getSession().setMaxInactiveInterval(10 * 60 * 60);
                uid.setMaxAge(30 * 24 * 3600);
                sid.setMaxAge(30 * 24 * 3600);
                return true;
            }
        }
        logger.debug("拦截：" + request.getServletPath());
        response.sendRedirect(request.getContextPath() + "/manage/tologin");
        return false;
    }

    void setServerSession(HttpSession session, User userdata) {
        //设置服务端需要长期保存的信息
        List<Menu> menuList = new ArrayList<Menu>();
        if (userdata.getRole() != null) {
            menuList = menuService.getMenuByRoleId(userdata.getRole().getId().toString()); //通过userid来读取对应的菜单列表\
        }
        session.setAttribute("menuList", menuList);
        session.setAttribute("nowTime", new Date());
        session.setAttribute("roleData", userdata.getRole());
    }
}
